package com.fadadianqi.logistics.admin.net;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Channel<T extends Packet> {

    private static final Log log = LogFactory.getLog(Channel.class);

    public static ThreadPoolExecutor executor;

    static {
        if (executor == null) {
            executor = new ThreadPoolExecutor(1, 3000, 15, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        }
    }

    ChannelHandler<T> handler;

    public Channel(ChannelHandler<T> handler) {
        this.handler = handler;
    }

    public void add(final T packet) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    handler.process(packet);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error(e.toString());
                }
            }
        };
        executor.execute(r);
    }
}
